import React, { Component } from 'react';
import { withRouter, Route } from 'react-router-dom';
import { Button, List, Tools, Icon, Checkbox, Tag } from 'weaver-mobile';
import { RouteLayout } from 'weaver-mobile-page';

import LabelManage from '../setting/labelManage';
import { TitleUtil, colorRgb } from '../../util';

const { callApi, getLabel } = Tools;
const { Item } = List;

/**
 * props说明:
 *  - path: 页面路由
 *  - onSubmit({key: [data], value: [data]}): 返回结果
 */
@withRouter
export default class SetTag extends Component {
  prefixCls = "email-set-tag";

  static defaultProps = {
    path: '/setTag',
  }

  constructor(props) {
    super(props);
    this.state = {
      data: [],
      selectedKeys: [undefined, undefined],
      selectedIds: [],
    };
  }

  componentDidMount() {
    window.isUmount = false;
    TitleUtil.setTitle(getLabel('30929','标记为'));
    this.getListData();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.path === nextProps.location.pathname) {
      TitleUtil.setTitle(getLabel('30929','标记为'));
    }
  }

  componentWillUnmount() {
    window.isUmount = true;
    TitleUtil.resetEmElement();
  }

  getListData = () => {
    const { params } = this.props;
    callApi({
      url: '/api/email/view/getViewPageMarkListByMobile',
      params: { ...params },
    }).then(res => {
      const { markList } = res;
      let selectedIds = [];
      let selectedKeys = [undefined, undefined];
      markList.forEach((group, index) => {
        const { multiple } = group;
        group.groupItems.forEach(item => {
          const { selected } = item;
          if (selected) {
            if (multiple) {
              selectedIds = [...selectedIds, item];
            } else {
              selectedKeys[index] = item;
            }
          }
        });
      });
      this.setState({ data: markList, selectedIds, selectedKeys });
    });
  }

  onSelectedKeys = (index, d, v) => {
    const { selectedKeys } = this.state;
    selectedKeys[index] = v ? d : undefined;
    this.setState({ selectedKeys: selectedKeys });
  }

  onSelectedIds = (d, v) => {
    const { selectedIds } = this.state;
    this.setState({ selectedIds: v ? [...selectedIds, d] : selectedIds.filter(m => m.id !== d.id) });
  }

  onCancelAllTag = () => {
    this.setState({ selectedIds: [] });
  }

  renderTitle = (data) => {
    const background = data.icon;
    const rgb = colorRgb(data.icon);
    const gray = (rgb[0] + rgb[1] + rgb[2]) / 3;
    const color = gray > 127 ? '#000' : '#fff';
    return (
      <Tag style={{ background, color }}>{data.label}</Tag>
    );
  }

  renderMoveList = (list, index, multiple) => (
    <div className={`${this.prefixCls}-list-body`}>
      {list.length > 0 && list.map(d => (
        <Item key={d.id} >
          <div className={`${this.prefixCls}-list-item`}>
            <div className={`${this.prefixCls}-list-item-label`}>
              {d.icon ? this.renderTitle(d) : d.label}
            </div>
            <div className={`${this.prefixCls}-list-item-checkbox`}>
              <Checkbox
                checked={multiple ? this.state.selectedIds.findIndex(i => i.id === d.id) !== -1 : (this.state.selectedKeys[index] && this.state.selectedKeys[index].key === d.key)}
                onChange={e => multiple ? this.onSelectedIds(d, e.target.checked) : this.onSelectedKeys(index, d, e.target.checked)}
              />
            </div>
          </div>
        </Item>
      ))}
    </div>
  )
  render() {
    const { path, onSubmit, history } = this.props;
    const { data, selectedKeys, selectedIds } = this.state;
    const route = `${path}/labelManage`;
    const filterData = data && data.filter(v => v.groupTitle) && data.filter(v => v.groupTitle)[0]
    return (
      <RouteLayout>
        <div className={`${this.prefixCls} wm-route-layout`} key="move-to">
          <div className={`${this.prefixCls}-view`}>
            {data && data.length > 0 && data.map((d, index) =>
              <List
                key={index}
                className={`${this.prefixCls}-list`}
                renderHeader={d.groupTitle ? (
                  <div className={`${this.prefixCls}-list-header`}>
                    <div className={`${this.prefixCls}-list-header-title`}>{d.groupTitle}</div>
                    <div className={`${this.prefixCls}-list-header-icon`}>
                      <Icon type="setting-up" onClick={() => history.push(route)} />
                    </div>
                  </div>
                ) : null}
                renderFooter={d.groupTitle ? (
                  <div className={`${this.prefixCls}-list-footer`}>
                    <span onClick={() => this.onCancelAllTag()}>{getLabel('31219','取消所有标签')}</span>
                  </div>
                ) : null}
              >
                {this.renderMoveList(d.groupItems, index, d.multiple)}
              </List>
            )}
          </div>
          <div className="btn-group">
            <Button type="primary" onClick={() => onSubmit && onSubmit([ ...selectedKeys.filter(d => d), ...selectedIds], filterData)}>
              {getLabel('826', '确定')}
            </Button>
          </div>
          <Route
            key="labelSetting"
            path={route}
            render={() => (
              <RouteLayout>
                <div
                  key="labelSetting"
                  className={`wm-route-layout`}
                >
                  <LabelManage title={getLabel('82728','标签管理')} path={route} refreshList={() => this.getListData()} />
                </div>
              </RouteLayout>
            )}
          />
        </div>
      </RouteLayout>
    );
  }
}